using M13.DataStructure;
using M13.Utility;
using System;
using System.Buffers;
using UnityEngine;

namespace M13.Game.World
{
    public class RegionDataArray
    {
        public DynamicExpansionArray<byte> DynamicExpansionArray { get; private set; }

        public RegionDataArray(byte[] regionSingularCompressedData)
        {
            DynamicExpansionArray = new DynamicExpansionArray<byte>(regionSingularCompressedData);
        }

        public void Recycle(byte[] regionSingularCompressedData)
        {
            DynamicExpansionArray.Recycle(regionSingularCompressedData);
        }

        /// <summary>
        /// �����������ڴ滯
        /// </summary>
        public ChunkDataBoot MemorizeChunkData(Chunk chunk)
        {
            ChunkDataBoot boot = new ChunkDataBoot();
            byte[] chm = Clzf2.Compress(chunk.ChunkHeightMap);
            byte[] ctim = Clzf2.Compress(chunk.ChunkTurfIdMap);
            byte[] cvm = Clzf2.Compress(chunk.ContinentalValueMap);

            boot.cvmDataLength = cvm.Length;
            boot.chmDataLength = chm.Length;
            boot.ctimDatalength = ctim.Length;
            boot.timeStamp = DateTime.Now.Ticks;

            //��������������࣬�������ݵĴ��˳��һ��Ҫͳһ
            byte[] chunkSingularCompressedData = RegionDataParser.Serialize(cvm, chm, ctim);
            boot.dataOffset = DynamicExpansionArray.AddArray(chunkSingularCompressedData, boot.GetTotalLength());
            ArrayPool<byte>.Shared.Return(chunkSingularCompressedData);

            ChunkReferencePool.Recycle(chunk);
            return boot;
        }

        /// <summary>
        /// ���ڴ������е��ֽ�����תΪ������
        /// </summary>
        /// <param name="chunkDataBoot"></param>
        /// <returns></returns>
        public Chunk ConcretizeChunkData(Vector2Int chunkLocalCoord, ChunkDataBoot chunkDataBoot)
        {
            Chunk chunk = null;
            if (ChunkReferencePool.GetPoolIrCount() > 0) 
            {
                chunk = (Chunk)ChunkReferencePool.Reuse();
            }
            else
            {
                chunk = new Chunk();
            }
            byte[] cvm;
            byte[] ctim;
            byte[] chm;
            byte[] chunkSingularCompressedData = null;
            DynamicExpansionArray.GetArrays(out chunkSingularCompressedData, chunkDataBoot.dataOffset, chunkDataBoot.GetTotalLength(), true);
            RegionDataParser.Deserialize(chunkLocalCoord, chunkSingularCompressedData, chunkDataBoot, out cvm, out chm, out ctim);
            chunk.Init(chunkLocalCoord, cvm, chm, ctim);
            return chunk;
        }

        
    }
}